package com.ykzhujiang.lovespirit.labor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ykzhujiang.lovespirit.util.Utility;

public class FudanLabor extends Labor {
	public int Login(String userid, String pw) {
		utmpuserid = userid;
		utmpuserpw = pw;
		while (System.currentTimeMillis() - last_login_time < 5000) {
			try {
				logger.info("Sleep for next login");
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				logger.warning(e.toString());
				logger.warning(e.getMessage());
			}
		}
		last_login_time = System.currentTimeMillis();
		String ltext = Utility.GetURLText(url_login + "id=" + utmpuserid
				+ "&pw=" + utmpuserpw, connect_times);
		if (ltext == null)
			return -1;
		Pattern p = Pattern.compile(cookie_pattern);
		Matcher m = p.matcher(ltext);
		if (m.find()) {
			utmpnum = m.group(1);
			utmpkey = m.group(2);
			utmpuserid = m.group(3);
		} else {
			logger.info("Login Fail");
			return -1;
		}
		logger.info("Login Success");
		logger.info("utmpnum: " + utmpnum);
		logger.info("utmpkey: " + utmpkey);
		logger.info("utmpuserid: " + utmpuserid);
		return 0;
	}

	public int Post(String title, String text) {

		while (System.currentTimeMillis() - last_post_time < 5000) {
			try {
				logger.info("Sleep for next post");
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				logger.warning(e.toString());
				logger.warning(e.getMessage());
			}
		}
		last_post_time = System.currentTimeMillis();
		try {

			HttpURLConnection connection = (HttpURLConnection) Utility
					.GetURLConnection(url_post, connect_times);
			if (connection == null)
				return -1;
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestProperty("Cookie", "utmpnum=" + utmpnum
					+ "; utmpkey=" + utmpkey + "; utmpuserid=" + utmpuserid);

			PrintWriter out = new PrintWriter(connection.getOutputStream());
			String pboard = "board=" + URLEncoder.encode(this.board, "GBK");
			String ptitle = "title=" + URLEncoder.encode(title, "GBK");
			String ptext = "text=" + URLEncoder.encode(text, "GBK");

			out.println(pboard + "&" + ptitle + "&" + ptext);
			out.close();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = in.readLine()) != null) {
				sb.append(line);
				sb.append("\r\n");
			}
			in.close();
			Pattern p = Pattern.compile(post_fail_pattern);
			Matcher m = p.matcher(sb.toString());
			if (m.find()) {
				if (Login(utmpuserid, utmpuserpw) != -1) {
					return Post(title, text);
				} else {
					logger.info("Post Fail");
					return -1;
				}
			}
			logger.info("Post Success");

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			logger.warning(e.toString());
			logger.warning(e.getMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.warning(e.toString());
			logger.warning(e.getMessage());
		}
		return 0;
	}

	public int Fetch(int page_num) {

		int count = 0;
		String url = url_text;
		while (count++ < page_num && url != null) {
			String text = Utility.GetURLText(url, connect_times);
			if (text == null) {
				return -1;
			}
			Pattern p = Pattern.compile(thread_pattern);
			Matcher m = p.matcher(text);
			while (m.find()) {
				String raw = url_root + m.group(0);
				if (!files.contains(raw)) {
					files.add(raw);
				}
			}
			p = Pattern.compile(page_pattern);
			m = p.matcher(text);
			if (m.find()) {
				url = url_root + m.group(0);
			} else {
				url = null;
			}
		}
		return 0;
	}

	public void SetBoard(String board) {
		this.board = board;
		thread_pattern = "bbstcon\\?board=" + board + "&file=.*?(?=>)";
		page_pattern = "bbstdoc\\?board=" + board + "&start=.*?(?=>)";
		url_text = "http://bbs.fudan.edu.cn/cgi-bin/bbs/bbstdoc?board=" + board;
		url_root = "http://bbs.fudan.edu.cn/cgi-bin/bbs/";
	}

	public String GetBorad() {
		return board;
	}

	private String board = "Magpie_Bridge";

	private String thread_pattern = "bbstcon\\?board=" + board
			+ "&file=.*?(?=>)";

	private String page_pattern = "bbstdoc\\?board=" + board
			+ "&start=.*?(?=>)";

	private String url_text = "http://bbs.fudan.edu.cn/cgi-bin/bbs/bbstdoc?board="
			+ board;

	private String url_root = "http://bbs.fudan.edu.cn/cgi-bin/bbs/";

	private static String utmpnum = "";

	private static String utmpkey = "";

	private static String utmpuserid = "";

	private static String utmpuserpw = "";

	private long last_post_time = 0;

	private long last_login_time = 0;

	private String url_login = "http://bbs.fudan.edu.cn/cgi-bin/bbs/bbslogin?";

	private String url_post = "http://bbs.fudan.edu.cn/cgi-bin/bbs/bbssnd";

	private String cookie_pattern = "(?s).*?utmpnum=(\\d{1,4}?)(?=')(?s).*?utmpkey=(\\d{1,10}?)(?=')(?s).*?utmpuserid=(\\w{1,12}?)(?=')(?s).*?";

	private String post_fail_pattern = "匆匆过客不能发表文章";

	// private static Logger logger=Logger.getLogger(FudanLabor.class);
	private static final Logger logger = Logger.getLogger(FudanLabor.class.getName());

}
